package com.itlong.cloud.controller.jd.elevator;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.itlong.cloud.POJO.DTO.app.AppCallLiftSaveDTO;
import com.itlong.cloud.POJO.DTO.common.PadFaceSyncDataDTO;
import com.itlong.cloud.POJO.DTO.property.IotCloudElevatorStateDTO;
import com.itlong.cloud.POJO.DTO.sdk.CloudElevatorSDKServerSendCommandDTO;
import com.itlong.cloud.POJO.DTO.sdk.CloudElevatorSDKSpecialUseModelDTO;
import com.itlong.cloud.POJO.DTO.sdk.jd.*;
import com.itlong.cloud.POJO.PO.DeviceElevatorInfoPO;
import com.itlong.cloud.POJO.VO.SDKMessageVO;
import com.itlong.cloud.POJO.VO.jd.JDResultVO;
import com.itlong.cloud.POJO.VO.property.CloudElevatorVO;
import com.itlong.cloud.POJO.VO.sdk.SDKJDAttriButeVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.*;
import com.itlong.cloud.enumerate.ecode.SDKErrorCodeEnum;
import com.itlong.cloud.enumerate.jd.JDCodEnum;
import com.itlong.cloud.equip.app.IAppDeviceServiceClient;
import com.itlong.cloud.equip.app.IAppVisitorPassCodeRecordServiceClient;
import com.itlong.cloud.equip.property.IPadFaceSyncDataServiceClient;
import com.itlong.cloud.equip.sdk.ICloudElevatorSDKServerCloudServiceClient;
import com.itlong.cloud.equip.sdk.ISDKJdServiceClient;
import com.itlong.cloud.iottp.IIOTHwServiceClient;
import com.itlong.cloud.iottp.IIotServerServiceClient;
import com.itlong.cloud.iottp.IIotVisitorFaceServiceClient;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.app.IAppHomeServiceClient;
import com.itlong.cloud.user.app.IAppMineServiceClient;
import com.itlong.cloud.utils.encrypt.DesEncryptUtil;
import com.itlong.cloud.utils.network.https.HttpsPost;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * <desc>
 * 京东接入云电梯Controller
 * </desc>
 *
 * @createDate 2020/08/03
 */
@RestController
@RequestMapping
public class JDCloudElevatorController extends   JDCloudDeviceBaseController{

    private static Logger log = LoggerFactory.getLogger(JDCloudElevatorController.class);

    @Autowired
    private IIOTHwServiceClient iiotHwServiceClient;
    @Autowired
    private IIotVisitorFaceServiceClient iIotVisitorFaceServiceClient;
    @Autowired
    private IIotServerServiceClient iIotServerServiceClient;

    @Autowired
    private IAppVisitorPassCodeRecordServiceClient iAppVisitorPassCodeRecordServiceClient;
    @Autowired
    private IAppDeviceServiceClient iAppDeviceServiceClient;
    @Autowired
    private IAppMineServiceClient iAppMineServiceClient;
    @Autowired
    private IAppHomeServiceClient iAppHomeServiceClient;


    @Autowired
    private IPadFaceSyncDataServiceClient iPadFaceSyncDataServiceClient;
    @Autowired
    private ICloudElevatorSDKServerCloudServiceClient iCloudElevatorSDKServerCloudServiceClient;
    @Autowired
    private ISDKJdServiceClient isdkJdServiceClient;
    @Autowired
    private RedisService redisService;

    /**
     * <desc>
     * 设备服务调用
     * <desc/>
     *
     * @param request
     * @return
     * @author caoshuai
     * @createDate 2020/08/03
     */

    @RequestMapping(value = "/device/service/invoke", method = RequestMethod.POST)
    public Object service(HttpServletRequest request) {
        long startTime = System.currentTimeMillis();
        //定义jd默认返回值
        JDResultVO result = new JDResultVO(200);
        //处理参数
        JDCloudElevatorServiceDTO jdCloudElevatorServiceDto = JSON.parseObject(request.getAttribute("jsonStr").toString(), JDCloudElevatorServiceDTO.class);
        if (StringUtils.isBlank(jdCloudElevatorServiceDto.getDeviceId())) {
            return new JDResultVO(JDCodEnum.REQUIRED_PARAMETER_IS_EMPTY.getCode());
        }
        log.info("【service方法中参数】" + (jdCloudElevatorServiceDto.toString()));
        //获取电梯设备信息
        DeviceElevatorInfoPO elevatorInfoPO = iCloudElevatorSDKServerCloudServiceClient.getElevatorByJDDeviceUnique(jdCloudElevatorServiceDto.getDeviceId());
        if (elevatorInfoPO == null || StringUtils.isBlank(elevatorInfoPO.getDeviceUnique())) {
            log.error(String.format("通过JD设备ID:%s未获取到我司关联设备号", jdCloudElevatorServiceDto.getDeviceId()));
            return new JDResultVO(JDCodEnum.DEVICE_NOT_EXIST_OR_UNALLOWABL.getCode());
        }

        switch (jdCloudElevatorServiceDto.getService()) {
            case SET_MODEL:
                CloudElevatorSDKSpecialUseModelDTO jdSpecialUseModelDTO = new CloudElevatorSDKSpecialUseModelDTO();
                jdSpecialUseModelDTO.setModel(JSON.parseObject(jdCloudElevatorServiceDto.getArgs(), HashMap.class).get("mode") + "");
                result = setModel(elevatorInfoPO.getDeviceUnique(), jdSpecialUseModelDTO);
                //保存生成操作日志所需信息 详细描述和接口类别
                request.setAttribute("remark", jdCloudElevatorServiceDto.getDeviceId() + "设置专梯模式");

                break;
            case OPEN_FLOOR:

                JDElevatorOpenOrAutoRegisterDTO jdElevatorOpenOrAutoRegisterDTO;
                jdElevatorOpenOrAutoRegisterDTO = JSON.parseObject(jdCloudElevatorServiceDto.getArgs(), JDElevatorOpenOrAutoRegisterDTO.class);
                jdElevatorOpenOrAutoRegisterDTO.setProjectId(elevatorInfoPO.getProjectId());
                jdElevatorOpenOrAutoRegisterDTO.setDeviceId(jdCloudElevatorServiceDto.getDeviceId());
                log.info("【openFloor方法中参数】" + (jdCloudElevatorServiceDto.toString()));
                result = openFloor(elevatorInfoPO, jdElevatorOpenOrAutoRegisterDTO);
                //保存 详细描述和接口类别
                request.setAttribute("remark", jdCloudElevatorServiceDto.getDeviceId() + "开放楼层" );
                break;
            case RESERVE:
                JDCloudDeviceDTO jdCloudDeviceDTO;
                jdCloudDeviceDTO = JSON.parseObject(jdCloudElevatorServiceDto.getArgs(), JDCloudDeviceDTO.class);
                jdCloudDeviceDTO.setProjectId(elevatorInfoPO.getProjectId());
                jdCloudDeviceDTO.setDeviceId(jdCloudElevatorServiceDto.getDeviceId());
                result = reserve(elevatorInfoPO, jdCloudDeviceDTO);
                //保存 详细描述和接口类别
                request.setAttribute("remark", jdCloudElevatorServiceDto.getDeviceId() + "预约乘梯");
                break;
            case DOOR_CTRL:
                JDCloudDeviceDTO cloudDeviceDTO = JSON.parseObject(jdCloudElevatorServiceDto.getArgs(), JDCloudDeviceDTO.class);
                cloudDeviceDTO.setProjectId(elevatorInfoPO.getProjectId());
                result = doorCtrl(elevatorInfoPO.getDeviceUnique(), cloudDeviceDTO);
                //保存 详细描述和接口类别
                request.setAttribute("remark", jdCloudElevatorServiceDto.getDeviceId() + "电梯门控制");
                break;
            case DEVICE_REPORT_CTRL:
                result = deviceReportCtrl(elevatorInfoPO.getDeviceUnique(), jdCloudElevatorServiceDto.getArgs(), jdCloudElevatorServiceDto.getDeviceId());
                //保存 详细描述和接口类别
                request.setAttribute("remark", jdCloudElevatorServiceDto.getDeviceId() + "电梯状态上报控制");
                break;
            case ADD_USER:
                result = addUser(jdCloudElevatorServiceDto.getArgs(),jdCloudElevatorServiceDto.getId());
                //保存 详细描述和接口类别
                request.setAttribute("remark", jdCloudElevatorServiceDto.getDeviceId() + "人脸业主注册");
                break;
            case UPDATE_USER:
                result = updateUser(jdCloudElevatorServiceDto.getArgs(),jdCloudElevatorServiceDto.getId());
                //保存 详细描述和接口类别
                request.setAttribute("remark", jdCloudElevatorServiceDto.getDeviceId() + "人脸业主修改");
                break;
            case REMOVE_USER:
                result = removeUser(jdCloudElevatorServiceDto.getArgs(),jdCloudElevatorServiceDto.getId(), elevatorInfoPO.getProjectId());
                //保存 详细描述和接口类别
                request.setAttribute("remark", jdCloudElevatorServiceDto.getDeviceId() + "人脸业主修改");
                break;
            case ADD_VISITOR:
                result = addVisitor(jdCloudElevatorServiceDto.getArgs(),jdCloudElevatorServiceDto.getId());
                //保存 详细描述和接口类别
                request.setAttribute("remark", jdCloudElevatorServiceDto.getDeviceId() + "人脸访客注册");
                break;
            case ELEVATOR_AUTH_ALTER:
                result = elevatorAuthAlter(jdCloudElevatorServiceDto.getArgs(),jdCloudElevatorServiceDto.getId());
                //保存 详细描述和接口类别
                request.setAttribute("remark", jdCloudElevatorServiceDto.getDeviceId() + "乘梯权限变更");
                break;
            case GET_ALLELEVATOR_INFO:
                result = getAllElevatorInfo(jdCloudElevatorServiceDto.getArgs(),jdCloudElevatorServiceDto.getId());
                //保存 详细描述和接口类别
                request.setAttribute("remark", jdCloudElevatorServiceDto.getDeviceId() + "乘梯权限信息查询");
                break;

            default:
                log.error("没有服务名称为:" + jdCloudElevatorServiceDto.getService());
                result.setCode(404);
                result.setMessage("service not found");
                break;
        }
        //保存生成操作日志所需信息
        request.setAttribute("portType", LogDescConstant.SDK_CLOUD_ELEVATOR_TYPE_LOG_DESC);
        //赋值id
        result.setId(jdCloudElevatorServiceDto.getId());
        long endTime = System.currentTimeMillis();
        log.info("【请求时间】" + (endTime - startTime));
        return result;

    }

    /**
     * <desc>
     * 设置电梯工作模式
     * <desc/>
     *
     * @param deviceUnique
     * @param jdElevatorSpecialUseModelDTO
     * @return
     * @author caoshuai
     * @createDate 2020/08/03
     */
    private JDResultVO setModel(String deviceUnique, CloudElevatorSDKSpecialUseModelDTO jdElevatorSpecialUseModelDTO) {

        try {
            CloudElevatorVO vo = iAppDeviceServiceClient.getCallElevatorInfo(deviceUnique);
            String iotProductKey = "";
            if (vo != null && vo.getIotProductKey() != null) {
                iotProductKey = vo.getIotProductKey();
            }
            //判断当前设备是否在线，如不在线返回失败
            String isOnline = iIotServerServiceClient.batchGetDeviceState(iotProductKey, deviceUnique);
            //判断设备是否在线
            if (isOnline == null || (isOnline != null && !isOnline.equals(IotDeviceStatusEnum.ONLINE.getType()))) {
                return new JDResultVO(JDCodEnum.CLOUD_ELEVATOR_OUT_LINE.getCode());
            }

            iAppDeviceServiceClient.setCloudElevatorSpecialUseModel(deviceUnique, jdElevatorSpecialUseModelDTO.getModel());
        } catch (Exception e) {
            throw new DataAccessException("【JD_云电梯_setModel】设置专梯模式异常", e);
        }
        return new JDResultVO(200);
    }

    /**
     * <desc>
     * 开放楼层服务
     * <desc/>
     *
     * @param jdElevatorOpenOrAutoRegisterDTO
     * @param elevatorInfoPO
     * @return
     * @author caoshuai
     * @createDate 2020/08/04
     */
    private JDResultVO openFloor(DeviceElevatorInfoPO elevatorInfoPO, JDElevatorOpenOrAutoRegisterDTO jdElevatorOpenOrAutoRegisterDTO) {
        Long startTime = System.currentTimeMillis();
        String deviceUnique = elevatorInfoPO.getDeviceUnique();
        //时间参数最大值为600最小值为0
        final Integer timeMax = 600;
        final Integer timeMin = 0;
        if (null == jdElevatorOpenOrAutoRegisterDTO.getTime()) {
            jdElevatorOpenOrAutoRegisterDTO.setTime(0);
        }
        if (StringUtils.isBlank(jdElevatorOpenOrAutoRegisterDTO.getOpenId())){
            return new JDResultVO(JDCodEnum.PARAMETER_INVALID.getCode());
        }
        if (jdElevatorOpenOrAutoRegisterDTO.getTime() > timeMax || jdElevatorOpenOrAutoRegisterDTO.getTime() < timeMin) {
            return new JDResultVO(JDCodEnum.PARAMETER_INVALID.getCode());
        }
        Long s1 = System.currentTimeMillis();
        CloudElevatorVO vo = iAppDeviceServiceClient.getCallElevatorInfo(deviceUnique);
        String iotProductKey = "";
        if (vo != null && vo.getIotProductKey() != null) {
            iotProductKey = vo.getIotProductKey();
        }
        Long s2 = System.currentTimeMillis();
        log.info("【batchGetDeviceState】>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + (s2 - s1));
        //判断当前设备是否在线，如不在线返回失败
        String isOnline = iIotServerServiceClient.batchGetDeviceState(iotProductKey, deviceUnique);
        //判断设备是否在线
        if (isOnline == null || (isOnline != null && !isOnline.equals(IotDeviceStatusEnum.ONLINE.getType()))) {
            return new JDResultVO(JDCodEnum.CLOUD_ELEVATOR_OUT_LINE.getCode());
        }
        Long s22 = System.currentTimeMillis();
        log.info("【batchGetDeviceState】>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + (s22 - s2));
        try {
            //获取真实楼层
            Map<String, Object> floor = iCloudElevatorSDKServerCloudServiceClient.getFloorNumAndNaturalFloorByLogicFloor(jdElevatorOpenOrAutoRegisterDTO.getFloor(), deviceUnique);

            if (floor == null || floor.get("floors") == null || floor.get("naturals") == null) {
                return new JDResultVO(JDCodEnum.PARAMETER_INVALID.getCode());
            }

            //调用IOT呼梯
            iAppDeviceServiceClient.openOrAutoRegister(deviceUnique,
                    CloudElevatorSourceEnum.ITLONG_CLOUD_ELEVATOR.getDescription(),
                    floor.get("floors").toString(), CloudElevatorCallTypeEnum.IN.getType(), jdElevatorOpenOrAutoRegisterDTO.getTime(), CallElevatorSourceTypeEnum.ROBOT.getType(), null, null);

            //装配呼梯记录对象
            AppCallLiftSaveDTO saveDTO = new AppCallLiftSaveDTO();
            saveDTO.setDeviceUnique(deviceUnique);
            saveDTO.setToFloor(floor.get("naturals").toString());
            saveDTO.setProjectId(jdElevatorOpenOrAutoRegisterDTO.getProjectId());
            saveDTO.setSource(CallElevatorRecordSourceEnum.CLOUD.getType());
            saveDTO.setUserId(jdElevatorOpenOrAutoRegisterDTO.getOpenId());
            iAppHomeServiceClient.saveCallLiftRecord(saveDTO);
            Long s4 = System.currentTimeMillis();
            //预约呼梯成功后上报呼梯记录
            Date nowTime = new Date();
            JDPassRecordDTO jdPassRecordDTO = new JDPassRecordDTO();
            jdPassRecordDTO.setUserId(jdElevatorOpenOrAutoRegisterDTO.getOpenId());
            //京东物模型定义 "1"为预约呼梯 "2":为人脸识别
            jdPassRecordDTO.setPassTime(nowTime.getTime());
            jdPassRecordDTO.setPassType("1");
            jdPassRecordDTO.setImageStr("");
            jdPassRecordDTO.setImageType("");
            jdPassRecordDTO.setDeviceId(jdElevatorOpenOrAutoRegisterDTO.getDeviceId());
            new Thread(() -> {
                try{
                    iCloudElevatorSDKServerCloudServiceClient.reportPassRecord(jdPassRecordDTO);
                } catch (Exception e){
                    throw new DataAccessException("【开放楼层】上报通行记录失败", e);
                }
            }).start();
            Long endTime = System.currentTimeMillis();
            log.info("【方法执行时间】" + (endTime - startTime));
            return new JDResultVO(JDCodEnum.SUCCESS.getCode());
        } catch (Exception e) {
            throw new DataAccessException("【JD_云电梯_openFloor】呼叫电梯异常", e);
        }
    }

    /**
     * <desc>
     * 预约乘梯
     * <desc/>
     *
     * @param jdCloudDeviceDTO
     * @param elevatorInfoPO
     * @return
     * @author caoshuai
     * @createDate 2020/08/04
     */
    private JDResultVO reserve(DeviceElevatorInfoPO elevatorInfoPO, JDCloudDeviceDTO jdCloudDeviceDTO) {
        String deviceUnique = elevatorInfoPO.getDeviceUnique();
        try {
            //获取真实楼层
            Map<String, Object> floor = iCloudElevatorSDKServerCloudServiceClient.getFloorNumByLogicFloor(jdCloudDeviceDTO.getGotoFloor(),
                    jdCloudDeviceDTO.getStartingFloor(), deviceUnique);
            if (floor == null || floor.get("goFloor") == null || floor.get("fromFloor") == null || StringUtils.isBlank(jdCloudDeviceDTO.getOpenId())) {
                return new JDResultVO(JDCodEnum.PARAMETER_INVALID.getCode());
            }
            //验证楼层是否超出范围
            if (Integer.valueOf(floor.get("goNaturalFloor").toString()) > elevatorInfoPO.getFloorNoMax() ||
                    Integer.valueOf(floor.get("fromNaturalFloor").toString()) > elevatorInfoPO.getFloorNoMax() ||
                    Integer.valueOf(floor.get("goNaturalFloor").toString()) < elevatorInfoPO.getFloorNo() ||
                    Integer.valueOf(floor.get("fromNaturalFloor").toString()) < elevatorInfoPO.getFloorNo()) {
                return new JDResultVO(JDCodEnum.FLOOR_OUT_RANGE.getCode());
            }
            CloudElevatorVO vo = iAppDeviceServiceClient.getCallElevatorInfo(deviceUnique);
            String iotProductKey = "";
            if (vo != null && vo.getIotProductKey() != null) {
                iotProductKey = vo.getIotProductKey();
            }
            //判断当前设备是否在线，如不在线返回失败
            String isOnline = iIotServerServiceClient.batchGetDeviceState(iotProductKey, deviceUnique);
            //判断设备是否在线
            if (isOnline == null || (isOnline != null && !isOnline.equals(IotDeviceStatusEnum.ONLINE.getType()))) {
                return new JDResultVO(JDCodEnum.CLOUD_ELEVATOR_OUT_LINE.getCode());
            }

            //调用IOT呼梯
            iAppDeviceServiceClient.cloudElevatorCall(deviceUnique,
                    CloudElevatorSourceEnum.ITLONG_CLOUD_ELEVATOR.getDescription(),
                    floor.get("fromFloor").toString(), floor.get("goFloor").toString(), null,
                    CloudElevatorCallTypeEnum.OUT.getType(), null, CallElevatorSourceTypeEnum.APP.getType(), null, null, null, null, null, null, "");


            //装配呼梯记录对象
            AppCallLiftSaveDTO saveDTO = new AppCallLiftSaveDTO();
            saveDTO.setDeviceUnique(deviceUnique);
            saveDTO.setFromFloor(floor.get("fromNaturalFloor").toString());
            saveDTO.setToFloor(floor.get("goNaturalFloor").toString());
            saveDTO.setProjectId(jdCloudDeviceDTO.getProjectId());

            saveDTO.setSource(CallElevatorRecordSourceEnum.CLOUD.getType());
            saveDTO.setUserId(jdCloudDeviceDTO.getOpenId());
            iAppHomeServiceClient.saveCallLiftRecord(saveDTO);
            //预约呼梯成功后上报呼梯记录
            JDPassRecordDTO jdPassRecordDTO = new JDPassRecordDTO();
            Date nowTime = new Date();
            jdPassRecordDTO.setUserId(jdCloudDeviceDTO.getOpenId());
            jdPassRecordDTO.setPassTime(nowTime.getTime());
            //京东物模型定义 "1"为预约呼梯 "2":为人脸识别
            jdPassRecordDTO.setPassType("1");
            jdPassRecordDTO.setImageStr("");
            jdPassRecordDTO.setImageType("");
            jdPassRecordDTO.setDeviceId(jdCloudDeviceDTO.getDeviceId());
            new Thread(() -> {
                try{
                    iCloudElevatorSDKServerCloudServiceClient.reportPassRecord(jdPassRecordDTO);
                } catch (Exception e){
                    throw new DataAccessException("【预约呼梯】上报通行记录失败", e);
                }
            }).start();
            return new JDResultVO(JDCodEnum.SUCCESS.getCode());
        } catch (Exception e) {
            throw new DataAccessException("【JD_云电梯_reserve】预约电梯异常", e);
        }
    }

    /**
     * <desc>
     * 电梯门控制
     * <desc/>
     *
     * @param cloudDeviceDTO
     * @param deviceUnique
     * @return
     * @author caoshuai
     * @createDate 2020/08/07
     */
    public JDResultVO doorCtrl(String deviceUnique, JDCloudDeviceDTO cloudDeviceDTO) {

        CloudElevatorSDKServerSendCommandDTO cloudElevatorSDKServerSendCommandDTO = new CloudElevatorSDKServerSendCommandDTO();
        cloudElevatorSDKServerSendCommandDTO.setDeviceUnique(deviceUnique);
        //默认是1：短按一次按钮
        Integer effectiveTime = 1;
        try {
            //校验参数
            if (StringUtils.isBlank(cloudDeviceDTO.getOpenCtrl()) && StringUtils.isBlank(cloudDeviceDTO.getCloseCtrl())) {
                return new JDResultVO(JDCodEnum.REQUIRED_PARAMETER_IS_EMPTY.getCode());
            }
            //处理验证参数并且赋值
            if (StringUtils.isNotBlank(cloudDeviceDTO.getOpenCtrl()) && Integer.valueOf(cloudDeviceDTO.getOpenCtrl()) >= 0) {
                cloudElevatorSDKServerSendCommandDTO.setType(1);
                effectiveTime = Integer.valueOf(cloudDeviceDTO.getOpenCtrl());
            }
            if (StringUtils.isNotBlank(cloudDeviceDTO.getCloseCtrl()) && Integer.valueOf(cloudDeviceDTO.getCloseCtrl()) >= 0) {
                cloudElevatorSDKServerSendCommandDTO.setType(2);
                effectiveTime = Integer.valueOf(cloudDeviceDTO.getCloseCtrl());
            }
            if (effectiveTime == null) {
                effectiveTime = 1;
            }
            // 大于"99"时，按"99"处理
            if (!(0 <= effectiveTime && effectiveTime <= 99)) {
                effectiveTime = 99;
            }

            CloudElevatorVO vo = iAppDeviceServiceClient.getCallElevatorInfo(deviceUnique);
            String iotProductKey = "";
            if (vo != null && vo.getIotProductKey() != null) {
                iotProductKey = vo.getIotProductKey();
            }
            //判断当前设备是否在线，如不在线返回失败
            String isOnline = iIotServerServiceClient.batchGetDeviceState(iotProductKey, deviceUnique);
            //判断设备是否在线
            if (isOnline == null || (isOnline != null && !isOnline.equals(IotDeviceStatusEnum.ONLINE.getType()))) {
                return new JDResultVO(JDCodEnum.CLOUD_ELEVATOR_OUT_LINE.getCode());
            }

            //类型 1开门 2关门
            int openType = 1;
            int closeType = 2;
            if (cloudElevatorSDKServerSendCommandDTO.getType() == openType) {
                iAppDeviceServiceClient.cloudElevatorCall(cloudElevatorSDKServerSendCommandDTO.getDeviceUnique(),
                        CloudElevatorSourceEnum.ITLONG_CLOUD_ELEVATOR.getDescription(),
                        null, null, null, CloudElevatorCallTypeEnum.OPEN.getType(), effectiveTime, CallElevatorSourceTypeEnum.ROBOT.getType(), null, null, null, null, null, null, "");
            }
            if (cloudElevatorSDKServerSendCommandDTO.getType() == closeType) {
                iAppDeviceServiceClient.cloudElevatorCall(cloudElevatorSDKServerSendCommandDTO.getDeviceUnique(),
                        CloudElevatorSourceEnum.ITLONG_CLOUD_ELEVATOR.getDescription(),
                        null, null, null, CloudElevatorCallTypeEnum.CLOSE.getType(), effectiveTime, CallElevatorSourceTypeEnum.ROBOT.getType(), null, null, null, null, null, null, "");
            }
            //判断电梯当前状态是否是开门，如果是开门则返回成功，否则返回失败
            boolean isOpen = false;
            int count = 0;
            while (count < 6) {
                Thread.sleep(500);
                IotCloudElevatorStateDTO dto = JsonUtil.toObject(redisService.getKeysForDevice(RedisConstant.REDIS_IOT_CLOUD_ELEVATOR_STATE_CACHE +
                        cloudElevatorSDKServerSendCommandDTO.getDeviceUnique()), IotCloudElevatorStateDTO.class);

                if (cloudElevatorSDKServerSendCommandDTO.getType() == openType) {
                    if (dto != null && StringUtils.isNotBlank(dto.getFrontDoor()) && (dto.getFrontDoor().equals("1") ||
                            dto.getFrontDoor().equals("3") || dto.getFrontDoor().equals("4"))) {
                        isOpen = true;
                        break;
                    }
                }
                if (cloudElevatorSDKServerSendCommandDTO.getType() == closeType) {
                    if (dto != null && StringUtils.isNotBlank(dto.getFrontDoor()) && (dto.getFrontDoor().equals("0") ||
                            dto.getFrontDoor().equals("2") || dto.getFrontDoor().equals("3"))) {
                        isOpen = true;
                        break;
                    }
                }

//                if (dto != null && StringUtils.isNotBlank(dto.getFrontDoor()) && (dto.getFrontDoor().equals("1") ||
//                        dto.getFrontDoor().equals("3") || dto.getFrontDoor().equals("4"))) {
//                    isOpen = true;
//                    break;
//                } else {
//                    //如从缓存中读取不到电梯的信息触发iot发送电梯控制指令
//                    iAppDeviceServiceClient.getCloudElevatorState(cloudElevatorSDKServerSendCommandDTO.getDeviceUnique(), "");
//                }
                if (!isOpen) {
                    //如从缓存中读取不到电梯的信息触发iot发送电梯控制指令
                    iAppDeviceServiceClient.getCloudElevatorState(cloudElevatorSDKServerSendCommandDTO.getDeviceUnique(), "");
                }
                count++;
            }
            Map<String, Object> result = new HashMap<>();
            result.put("isOpen", isOpen + "");
            if (isOpen) {
                return new JDResultVO(JDCodEnum.SUCCESS.getCode());
            } else {
                return new JDResultVO(JDCodEnum.PLATFORM_INTERNAL_EXCEPTION.getCode());
            }
        } catch (Exception e) {
            throw new DataAccessException("【JD_云电梯_doorCtrl】电梯门控制异常", e);
        }
    }

    /**
     * <desc>
     * 上报状态控制
     * <desc/>
     *
     * @param deviceUnique 设备号
     * @param args         入参
     * @param deviceId     JD设备号
     * @return
     * @author caoshuai
     * @createDate 2020/08/10
     */
    public JDResultVO deviceReportCtrl(String deviceUnique, String args, String deviceId) {


        try {
            CloudElevatorVO vo = iAppDeviceServiceClient.getCallElevatorInfo(deviceUnique);
            String iotProductKey = "";
            if (vo != null && vo.getIotProductKey() != null) {
                iotProductKey = vo.getIotProductKey();
            }
            //判断当前设备是否在线，如不在线返回失败
            String isOnline = iIotServerServiceClient.batchGetDeviceState(iotProductKey, deviceUnique);
            //判断设备是否在线
            if (isOnline == null || (isOnline != null && !isOnline.equals(IotDeviceStatusEnum.ONLINE.getType()))) {
                return new JDResultVO(JDCodEnum.CLOUD_ELEVATOR_OUT_LINE.getCode());
            }
            String openOrClose = JSON.parseObject(args, HashMap.class).get("openOrClose") + "";
            JDResultVO result = iCloudElevatorSDKServerCloudServiceClient.jdOpenOrCloseStateReport(deviceUnique, openOrClose, deviceId, appid, secret);
            return result;
        } catch (Exception e) {
            throw new DataAccessException("【SDK_云电梯_deviceReportCtrl】打开关闭上报状态异常", e);
        }
    }

    /**
     * <desc>
     * 京东推送数据接口
     * </desc>
     *
     * @param request
     * @return
     * @author Jiaqi.X
     * @createDate 2020/08/11
     */
    @RequestMapping("/data/push")
    public Object push(HttpServletRequest request) {
        try {
            String jsonStr = request.getAttribute("jsonStr").toString();
            JDPushDataDTO dto = JsonUtil.toObject(jsonStr, JDPushDataDTO.class);
            //检测设备id是否已绑定设备
            if (Integer.valueOf(dto.getType()) == 1 && isdkJdServiceClient.checkBindDeviceId(dto.getData().get("deviceId").toString(),
                    dto.getData().get("uniqueId").toString()) > 0) {
                return new JDResultVO(dto.getId(), JDCodEnum.DEVICE_REGISTER_ERROR.getCode());
            }
            if (isdkJdServiceClient.bindDeviceId(dto.getData().get("deviceId").toString(),
                    dto.getData().get("uniqueId").toString(), Integer.valueOf(dto.getType())) > 0) {
                //JD项目编号存储
                String jdProjectId = redisService.get(PlatformConstants.JD_PROJECT_ID);
                if (StringUtils.isNotBlank(jdProjectId)) {
                    boolean b = jdProjectId.equals(StringHandlerUtil.getProjectIdByDeviceUnique(dto.getData().get("uniqueId").toString()));
                    if (!b) {
                        redisService.set("JD_PROJECT_ID", StringHandlerUtil.getProjectIdByDeviceUnique(dto.getData().get("uniqueId").toString()));
                    }
                }else {
                    redisService.set("JD_PROJECT_ID", StringHandlerUtil.getProjectIdByDeviceUnique(dto.getData().get("uniqueId").toString()));
                }
                //推送京东设备状态
                Map<String, Object> params = new HashMap<>();
                params.put("id", LogicIdUtil.bussinessId());
                Map<String, Object> protocol = new HashMap<>();
                protocol.put("version", "1.0");
                protocol.put("name", "JD-IOT-ESTATE-DEVICE");
                Map<String, Object> client = new HashMap<>();
                client.put("appid", appid);
                Map<String, Object> param = new HashMap<>();
                //String jdDeviceId = iIotDeviceOnlineServiceClient.getJdDeviceId(deviceUnique, StringHandlerUtil.getDeviceTypeByDeviceUnique(deviceUnique));
                Map<String, Object> deviceInfo = isdkJdServiceClient.getDeviceInfo(dto.getData().get("uniqueId").toString(), StringHandlerUtil.getDeviceTypeByDeviceUnique(dto.getData().get("uniqueId").toString()));
                //判断当前设备是否在线，如不在线返回失败
                String iotProductKey = "";
                if (deviceInfo != null && deviceInfo.get("iotProductKey") != null) {
                    iotProductKey = deviceInfo.get("iotProductKey") + "";
                }
                String isOnline = iIotServerServiceClient.batchGetDeviceState(iotProductKey, dto.getData().get("uniqueId").toString());
                if (StringUtils.isNotBlank(dto.getData().get("deviceId").toString())) {
                    param.put("deviceId", dto.getData().get("deviceId").toString());
                    //判断设备是否在线
                    if (isOnline == null || (isOnline != null && !isOnline.equals(IotDeviceStatusEnum.ONLINE.getType()))) {
                        param.put("status", "0");
                    } else {
                        param.put("status", "1");
                    }
                    params.put("protocol", protocol);
                    params.put("client", client);
                    params.put("params", param);
                    try {
                        params = DesEncryptUtil.getJdSign(JsonUtil.toJSON(params), PlatformConstants.JD_CHANGEONLINESTATUS_URL, secret);
                        HttpsPost.doJdPost(jdUrl + PlatformConstants.JD_CHANGEONLINESTATUS_URL, JsonUtil.toJSON(params));
                    } catch (Exception e) {
                        log.error("【iot 绑定后推送上下线状态失败：】", e);
                    }
                }
                return new JDResultVO(dto.getId(), JDCodEnum.SUCCESS.getCode());
            } else {
                return new JDResultVO(dto.getId(), JDCodEnum.PLATFORM_INTERNAL_EXCEPTION.getCode());
            }
        } catch (Exception e) {
            throw new DataAccessException("【JD_云电梯_push】京东推送数据异常", e);
        }
    }

    /**
     * <desc>
     * 京东获取设备属性接口
     * </desc>
     *
     * @param request
     * @return
     * @author Jiaqi.X
     * @createDate 2020/08/11
     */
    @RequestMapping("/device/properties/get")
    public Object get(HttpServletRequest request) {
        try {
            String jsonStr = request.getAttribute("jsonStr").toString();
            JDGetDataDTO dto = JsonUtil.toObject(jsonStr, JDGetDataDTO.class);
            SDKJDAttriButeVO vo;
            Map<String, Object> result;
            Map<String, Object> jdResult = new HashMap<>();
            Map<String, Object> message = new HashMap<>();
            //查询设备华为云id
            String response;
            if (dto.getProperties().stream().filter(d -> d.equals("bindList")).findFirst().isPresent()) {
                //群控器
                vo = isdkJdServiceClient.initAtrributeVO(dto.getDeviceId(), 5);
                if (vo == null) {
                    return new JDResultVO(dto.getId(), JDCodEnum.DEVICE_NOT_EXIST_OR_UNALLOWABL.getCode());
                }
                Map<String, Object> deviceInfo = isdkJdServiceClient.getDeviceInfoByJDDeviceId(dto.getDeviceId(), 5);
                //判断当前设备是否在线，如不在线返回失败
                String iotProductKey = "";
                if (deviceInfo != null && deviceInfo.get("iotProductKey") != null) {
                    iotProductKey = deviceInfo.get("iotProductKey") + "";
                }
                //判断当前设备是否在线，如不在线返回失败
                String isOnline = iIotServerServiceClient.batchGetDeviceState(iotProductKey, deviceInfo.get("deviceUnique") + "");
                //判断设备是否在线
                if (isOnline == null || (isOnline != null && !isOnline.equals(IotDeviceStatusEnum.ONLINE.getType()))) {
                    return new JDResultVO(JDCodEnum.CLOUD_ELEVATOR_OUT_LINE.getCode());
                }
                String hwDeviceId = isdkJdServiceClient.getHwDeviceId(dto.getDeviceId(), 5);
                //组装获取群控器上下行按键数据
                message.put("sourceFrom", "itlong");
                message.put("snr", LogicIdUtil.bussinessId());
                message.put("timestamp", System.currentTimeMillis() + "");
                message.put("cmd", "1007");
                response = iiotHwServiceClient.pubDeviceMessageResponse("SettingService", "getButtonStatus", hwDeviceId, JsonUtil.toJSON(message));
                //此处转换可能有数据结构错误，需根据返回的reponse 拿到电梯返回的状态
                result = JsonUtil.toObject(response, HashMap.class);
                Map<String, Object> msgMap = JSON.parseObject(JSON.toJSONString(result.get("response")), Map.class);
                Map<String, Object> parasMap = JSON.parseObject(JSON.toJSONString(msgMap.get("paras")), Map.class);
                vo.setUp(StringHandlerUtil.getNullOrStringForObject(parasMap.get("up")));
                vo.setDown(StringHandlerUtil.getNullOrStringForObject(parasMap.get("down")));
                jdResult.put("properties", this.getProperties(dto.getProperties(), vo));
                return new JDResultVO(dto.getId(), JDCodEnum.SUCCESS.getCode(), jdResult);
            } else {
                //云电梯
                vo = isdkJdServiceClient.initAtrributeVO(dto.getDeviceId(), 1);
                if (vo == null) {
                    return new JDResultVO(dto.getId(), JDCodEnum.DEVICE_NOT_EXIST_OR_UNALLOWABL.getCode());
                }
                Map<String, Object> deviceInfo = isdkJdServiceClient.getDeviceInfoByJDDeviceId(dto.getDeviceId(), 1);
                //判断当前设备是否在线，如不在线返回失败
                String iotProductKey = "";
                if (deviceInfo != null && deviceInfo.get("iotProductKey") != null) {
                    iotProductKey = deviceInfo.get("iotProductKey") + "";
                }
                String isOnline = iIotServerServiceClient.batchGetDeviceState(iotProductKey, deviceInfo.get("deviceUnique") + "");
                //判断设备是否在线
                if (isOnline == null || (isOnline != null && !isOnline.equals(IotDeviceStatusEnum.ONLINE.getType()))) {
                    return new JDResultVO(JDCodEnum.CLOUD_ELEVATOR_OUT_LINE.getCode());
                }
                String hwDeviceId = isdkJdServiceClient.getHwDeviceId(dto.getDeviceId(), 1);
                //组装获取电梯状态数据
                message.put("sourceFrom", "itlong");
                message.put("snr", LogicIdUtil.bussinessId());
                message.put("timestamp", (new Date()).getTime() + "");
                message.put("cmd", "1004");
                response = iiotHwServiceClient.pubDeviceMessageResponse("SettingService", "getDeviceState", hwDeviceId, JsonUtil.toJSON(message));
                //此处转换可能有数据结构错误，需根据返回的reponse 拿到电梯返回的状态
                result = JsonUtil.toObject(response, HashMap.class);
                Map<String, Object> msgMap = JSON.parseObject(JSON.toJSONString(result.get("response")), Map.class);
                Map<String, Object> parasMap = JSON.parseObject(JSON.toJSONString(msgMap.get("paras")), Map.class);
                Map<String, String> paras = JSON.parseObject(JSONObject.toJSONString(parasMap), Map.class);
                Field[] fields = vo.getClass().getDeclaredFields();
                for (String key : paras.keySet()) {
                    for (Field f : fields) {
                        if (f.getName().equals(key)) {
                            f.setAccessible(true);
                            f.set(vo, paras.get(key));
                            break;
                        }
                    }
                }

//                vo.setFloor(StringHandlerUtil.getNullOrStringForObject(paras.get("floor")));
//                vo.setUpDown(StringHandlerUtil.getNullOrStringForObject(paras.get("upDown")));
//                vo.setFrontDoor(StringHandlerUtil.getNullOrStringForObject(paras.get("frontDoor")));
//                vo.setBackDoor(StringHandlerUtil.getNullOrStringForObject(paras.get("backDoor")));
//                vo.setEmergency(StringHandlerUtil.getNullOrStringForObject(paras.get("emergency")));
//                vo.setMode(StringHandlerUtil.getNullOrStringForObject(paras.get("mode")));
                //组装获取电梯楼层登记信息
                message.put("sourceFrom", "itlong");
                message.put("snr", LogicIdUtil.bussinessId());
                message.put("timestamp", (new Date()).getTime() + "");
                message.put("cmd", "1007");
                response = iiotHwServiceClient.pubDeviceMessageResponse("SettingService", "getButtonStatus", hwDeviceId, JsonUtil.toJSON(message));
                //此处转换可能有数据结构错误，需根据返回的reponse 拿到电梯返回的状态
                result = JsonUtil.toObject(response, HashMap.class);
                Map<String, Object> resultMap = JSON.parseObject(JSON.toJSONString(result.get("response")), Map.class);
                Map<String, Object> parasMapData = JSON.parseObject(JSON.toJSONString(resultMap.get("paras")), Map.class);
                Map<String, String> parasData = JSON.parseObject(JSONObject.toJSONString(parasMapData), Map.class);

                vo.setFloorRegister(StringHandlerUtil.getNullOrStringForObject(parasData.get("floor")));
                jdResult.put("properties", this.getProperties(dto.getProperties(), vo));
                return new JDResultVO(dto.getId(), JDCodEnum.SUCCESS.getCode(), jdResult);
            }
        } catch (Exception e) {
            throw new DataAccessException("【JD_云电梯_push】京东推送数据异常", e);
        }
    }

    /**
     * <desc>
     * 人脸业主注册
     * <desc/>
     *
     * @param args  入参
     * @param id    请求id
     * @return
     * @author pengwei
     * @createDate 2020/12/08
     */
    public JDResultVO addUser(String args,String  id) {
        try {
            JSONObject    argsJson  = JSON.parseObject(args);
            //手机号
            String   phoneNum  =  argsJson.getString("phoneNum");
            //真实姓名
            String   realName  =  argsJson.getString("realName");
            //性别
            String   gender  =  argsJson.getString("gender");
            //人脸图片
            String photoUrl = argsJson.getString("photoUrl");
            //支持传入的openId作为用户唯一标识
            String openId = argsJson.getString("openId");
            if ( StringUtils.isBlank(photoUrl) || StringUtils.isBlank(openId)) {
                return new JDResultVO(JDCodEnum.REQUIRED_PARAMETER_IS_EMPTY.getCode());
            }
            //JD项目编号获取
            String jdProjectId = redisService.get(PlatformConstants.JD_PROJECT_ID);
            argsJson.put("projectId",jdProjectId);
            //手机号码校验
            if (StringUtils.isNotBlank(phoneNum)){
                String regex = "^1[3|4|5|6|7|8|9]\\d{9}$";
                if (phoneNum.length() != 11 || !Pattern.compile(regex).matcher(phoneNum).matches()) {
                    return   new JDResultVO(JDCodEnum.PARAMETER_FORMAT_ERROR.getCode());
                }
                //查询手机号是否存在
                Integer result = iPropertyHouseHoldInfoServiceClient.getAppUserExistStatus(jdProjectId,phoneNum);
                if (result > 0) {
                    return   new JDResultVO(JDCodEnum.EXIST_PHONENO.getCode());
                }
            }
            //添加结果
            String   addRs = iPropertyHouseHoldInfoServiceClient.jdUserFaceReg(argsJson);
            if(addRs==null){
                return   new JDResultVO(JDCodEnum.FACE_REG_FAIL.getCode());
            }
            //保存图片
            JDResultVO saveRes = saveFace(photoUrl, jdProjectId, false, addRs, null, false);
            if (!JDCodEnum.SUCCESS.getCode().equals(saveRes.getCode())) {
                argsJson.put("userId", addRs);
                iPropertyHouseHoldInfoServiceClient.jdUserRealDel(argsJson);
                return saveRes;
            }
            PadFaceSyncDataDTO padFaceSyncDataDTO = new PadFaceSyncDataDTO();
            padFaceSyncDataDTO.setOperateType("1");
            padFaceSyncDataDTO.setAppUserIds(addRs);
            padFaceSyncDataDTO.setProjectId(jdProjectId);
            padFaceSyncDataDTO.setStatus("1");
            padFaceSyncDataDTO.setSourceSystem(4);
            padFaceSyncDataDTO.setPhotoUrl(photoUrl);
            iPadFaceSyncDataServiceClient.jdUpdatePhotoSync(padFaceSyncDataDTO);
            return   new JDResultVO(id,JDCodEnum.SUCCESS.getCode());
        } catch (Exception e) {
            throw new DataAccessException("【SDK_云电梯_addUser】注册业主人脸异常", e);
        }
    }


    /**
     * <desc>
     * 人脸业主修改
     * <desc/>
     *
     * @param args  入参
     * @param id    请求id
     * @return
     * @author pengwei
     * @createDate 2020/12/10
     */
    public JDResultVO updateUser(String args,String  id) {
        try {
            JSONObject    argsJson  = JSON.parseObject(args);
            //userId
            String   userId  =  argsJson.getString("openId");
            //手机号
            String   phoneNum  =  argsJson.getString("phoneNum");
            //真实姓名
            String   realName  =  argsJson.getString("realName");
            //性别
            String   gender  =  argsJson.getString("gender");
            //人脸图片
            String   photoUrl  =  argsJson.getString("photoUrl");
            if (
                    StringUtils.isBlank(userId) || StringUtils.isBlank(photoUrl)
                    ) {
                return new JDResultVO(JDCodEnum.REQUIRED_PARAMETER_IS_EMPTY.getCode());
            }
            //JD项目编号获取
            String jdProjectId = redisService.get(PlatformConstants.JD_PROJECT_ID);
            argsJson.put("projectId",jdProjectId);
            if(StringUtils.isNotBlank(phoneNum)){
                //手机号码校验
                String regex = "^1[3|4|5|6|7|8|9]\\d{9}$";
                if (phoneNum.length() != 11 || !Pattern.compile(regex).matcher(phoneNum).matches()) {
                    return   new JDResultVO(JDCodEnum.PARAMETER_FORMAT_ERROR.getCode());
                }
            }
            //处理结果
            JDResultVO   updateVo = iPropertyHouseHoldInfoServiceClient.jdUserUpdate(argsJson);
            if(!updateVo.getCode().equals(JDCodEnum.SUCCESS.getCode())){
                return   updateVo;
            }

            //保存图片
            JDResultVO   saveRes = saveFace(photoUrl,jdProjectId,false,userId,null,true);
            if (!JDCodEnum.SUCCESS.getCode().equals(saveRes.getCode())) {
                return saveRes;
            }
            PadFaceSyncDataDTO padFaceSyncDataDTO = new PadFaceSyncDataDTO();
            padFaceSyncDataDTO.setOperateType("0");
            padFaceSyncDataDTO.setAppUserIds(userId);
            padFaceSyncDataDTO.setProjectId(jdProjectId);
            padFaceSyncDataDTO.setStatus("1");
            padFaceSyncDataDTO.setSourceSystem(4);
            padFaceSyncDataDTO.setPhotoUrl(photoUrl);
            iPadFaceSyncDataServiceClient.jdUserDataSync(padFaceSyncDataDTO);
            iPadFaceSyncDataServiceClient.jdUpdatePhotoSync(padFaceSyncDataDTO);
            return   new JDResultVO(id,JDCodEnum.SUCCESS.getCode());
        } catch (Exception e) {
            throw new DataAccessException("【SDK_云电梯_updateUser】修改业主信息异常", e);
        }
    }

    /**
     * <desc>
     * 人脸业主删除
     * <desc/>
     *
     * @param args  入参
     * @param id    请求id
     * @return
     * @author pengwei
     * @createDate 2020/12/10
     */
    public JDResultVO removeUser(String args,String  id, String projectId) {
        try {
            JSONObject    argsJson  = JSON.parseObject(args);
            //userId
            String   userId  =  argsJson.getString("openId");
            if (StringUtils.isEmpty(userId)) {
                return new JDResultVO(JDCodEnum.REQUIRED_PARAMETER_IS_EMPTY.getCode());
            }
            new Thread(() -> {
                try {
                    //清除人脸以及ftp照片
                    iIotVisitorFaceServiceClient.deleteJdUserFace(userId, projectId);
                    //优先处理平板指令
                    iPadFaceSyncDataServiceClient.jdUserSyncForSDK(userId, projectId);
                    //注销用户发送设备端指令
                    iAppMineServiceClient.logOffUserForJdSdk(userId, projectId);
                } catch (Exception e) {
                    log.error("SDK删除用户处理异常");
                }
            }
            ).start();
            return   new JDResultVO(id,JDCodEnum.SUCCESS.getCode());
        } catch (Exception e) {
            throw new DataAccessException("【SDK_云电梯_deleteUser】删除业主信息异常", e);
        }
    }


    /**
     * <desc>
     * 人脸访客注册
     * <desc/>
     *
     * @param args  入参
     * @param id    请求id
     * @return
     * @author pengwei
     * @createDate 2020/12/08
     */
    public JDResultVO addVisitor(String args,String  id) {
        try {
            JSONObject    argsJson  = JSON.parseObject(args);
            //受访人userId
            String   userId  =  argsJson.getString("openId");
            //受访人姓名
            String   intervieweeName =  argsJson.getString("intervieweeName");
            //访客姓名
            String   visitorName     =  argsJson.getString("visitorName");
            //访客手机号--可传空
            String   visitorPhone  =  argsJson.getString("visitorPhone");
            //访问有效时长
            String   effectiveTime  =  argsJson.getString("effectiveTime");
            //人脸图片
            String   photoUrl  =  argsJson.getString("photoUrl");
            if (
                    StringUtils.isEmpty(userId)
                            || StringUtils.isEmpty(effectiveTime)
                            || StringUtils.isEmpty(photoUrl)
                    ) {
                return new JDResultVO(JDCodEnum.REQUIRED_PARAMETER_IS_EMPTY.getCode());
            }
            //校验访客姓名及被拜访访客姓名的字段长度
            if((StringUtils.isNotBlank(visitorName) && visitorName.length()>32)
                    ||(StringUtils.isNotBlank(intervieweeName) && intervieweeName.length()>32)){
                SDKMessageVO messageVO  =  new SDKMessageVO(SDKErrorCodeEnum.SDK_VISITOR_NAME_ERR.getErrorCode(),null,null,"");
                return  new  JDResultVO(messageVO.getMsgCode(),messageVO.getMsg());
            }

            if (StringUtils.isNotBlank(effectiveTime) && (Integer.parseInt(effectiveTime) >1440)){
                return new JDResultVO(JDCodEnum.VISITOR_EFFECTIVE_TIME_TOO_LONG.getCode());
            }
            //JD项目编号获取
            String jdProjectId = redisService.get(PlatformConstants.JD_PROJECT_ID);
            argsJson.put("projectId",jdProjectId);
            if(StringUtils.isNotEmpty(visitorPhone)){
                //手机号码校验
                String regex = "^1[3|4|5|6|7|8|9]\\d{9}$";
                if (visitorPhone.length() != 11 || !Pattern.compile(regex).matcher(visitorPhone).matches()) {
                    return   new JDResultVO(JDCodEnum.PARAMETER_FORMAT_ERROR.getCode());
                }
            }
            //添加结果
            String   passId = iPropertyHouseHoldInfoServiceClient.jdVisitorFaceReg(argsJson);
            if(passId==null){
                return   new JDResultVO(JDCodEnum.OWNER_DO_NOT_EXISTS_ERROR.getCode());
            }
            //保存图片
            JDResultVO   saveRes = saveFace(photoUrl,jdProjectId,true,null,passId,false);
            if (!JDCodEnum.SUCCESS.getCode().equals(saveRes.getCode())) {
                iAppVisitorPassCodeRecordServiceClient.deleteVisitorInfo(passId);
                return saveRes;
            }
            PadFaceSyncDataDTO padFaceSyncDataDTO = new PadFaceSyncDataDTO();
            padFaceSyncDataDTO.setOperateType("3");
            padFaceSyncDataDTO.setProjectId(jdProjectId);
            padFaceSyncDataDTO.setPassId(passId);
            padFaceSyncDataDTO.setStatus("1");
            padFaceSyncDataDTO.setSourceSystem(4);
            padFaceSyncDataDTO.setPhotoUrl(photoUrl);
            padFaceSyncDataDTO.setAppUserIds(passId);
            iPadFaceSyncDataServiceClient.jdUserDataSync(padFaceSyncDataDTO);
            iPadFaceSyncDataServiceClient.jdUpdatePhotoSync(padFaceSyncDataDTO);
            return new JDResultVO(id,JDCodEnum.SUCCESS.getCode());
        } catch (Exception e) {
            throw new DataAccessException("【SDK_云电梯_addVisitor】注册访客人脸异常", e);
        }
    }
    /**
     * <desc>
     * 业主乘梯权限变更
     * <desc/>
     *
     * @param args  入参
     * @param id    请求id
     * @return
     * @author pengwei
     * @createDate 2020/12/10
     */
    public JDResultVO elevatorAuthAlter(String args,String  id) {
        try {
            JSONObject    argsJson  = JSON.parseObject(args);
            //业主userId
            String   userId  =  argsJson.getString("openId");
            //电梯楼层列表
            String   elevatorList =  argsJson.getString("elevatorList");
            if (StringUtils.isEmpty(userId)|| StringUtils.isEmpty(elevatorList)) {
                return new JDResultVO(JDCodEnum.REQUIRED_PARAMETER_IS_EMPTY.getCode());
            }
            //JD项目编号获取
            String jdProjectId = redisService.get(PlatformConstants.JD_PROJECT_ID);
            //乘梯权限变更结果
            argsJson.put("projectId",jdProjectId);
            //请求id
            argsJson.put("id",id);
            JDResultVO   resVo  =  iPropertyHouseHoldInfoServiceClient.jdAuthAlter(argsJson);
            if(!JDCodEnum.SUCCESS.getCode().equals(resVo.getCode())){
                return resVo;
            }
            PadFaceSyncDataDTO padFaceSyncDataDTO = new PadFaceSyncDataDTO();
            padFaceSyncDataDTO.setOperateType("1");
            padFaceSyncDataDTO.setAppUserIds(userId);
            padFaceSyncDataDTO.setProjectId(jdProjectId);
            padFaceSyncDataDTO.setStatus("1");
            padFaceSyncDataDTO.setSourceSystem(4);
            List<String>  padUniqueList = (List<String>)resVo.getParams();
            if(padUniqueList!=null&&padUniqueList.size()>0){
                padFaceSyncDataDTO.setDeviceUniques(Joiner.on(",").join(padUniqueList));
            }
            iPadFaceSyncDataServiceClient.jdUserDataSync(padFaceSyncDataDTO);
            resVo.setParams(null);
            return  resVo;
        } catch (Exception e) {
            throw new DataAccessException("【SDK_云电梯_elevatorAuthAlter】权限变更异常", e);
        }
    }
    /**
     * <desc>
     * 业主获取权限电梯和对应楼层信息
     * <desc/>
     *
     * @param args  入参
     * @param id    请求id
     * @return
     * @author pengwei
     * @createDate 2020/12/11
     */
    public JDResultVO getAllElevatorInfo(String args,String  id) {
        try {
            JSONObject    argsJson  = JSON.parseObject(args);
            //业主userId
            String   userId  =  argsJson.getString("openId");
            //JD项目编号获取
            String jdProjectId = redisService.get(PlatformConstants.JD_PROJECT_ID);
            argsJson.put("projectId",jdProjectId);
            //请求id
            argsJson.put("id",id);
            //查询结果
            JDResultVO   resVo  =  iPropertyHouseHoldInfoServiceClient.getAllElevatorInfo(argsJson);
            return   resVo;
        } catch (Exception e) {
            throw new DataAccessException("【SDK_云电梯_getAllElevatorInfo】业主获取权限电梯和对应楼层异常", e);
        }
    }

    /**
     * <desc>
     *      根据传入的图片地址获取base64
     * </desc>
     *
     * @param imageUrl 图片地址
     * @return
     * @Author Zhu.yj
     * @createDate  2021/1/20
     */
    public static String imageToBase64ByOnline(String imageUrl) {
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            // 创建URL
            URL url = new URL(imageUrl);
            byte[] bytes = new byte[1024];
            // 创建链接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            //设置请求头，不然有些图片返回403
            connection.setRequestProperty("User-agent", "Mozilla/4.0");
            InputStream inputStream;
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK){
                inputStream = connection.getInputStream();
                // 将内容读取内存中
                int len = 0;
                while ((len = inputStream.read(bytes)) != -1) {
                    data.write(bytes, 0, len);
                }
                // 关闭流
                inputStream.close();
                // 对字节数组Base64编码
                BASE64Encoder encoder = new BASE64Encoder();
                return encoder.encode(data.toByteArray());
            }
        } catch (IOException e) {
            throw new DataAccessException("解析网络图片失败", e);
        }
        return null;
    }

    public static void main(String[] args) throws IOException {
//        String a = "[{service_id=InfoService, event_time=20200213T061459Z, properties={floor=3, frontDoor=0, mode=0, msg=success, msgCode=0, timestamp=1581574499439, upDown=0}}]";
//        List<Map<String,Object>> list = JsonUtil.decode(a, new TypeReference<List<Map<String, Object>>>() {});
//        System.out.println(a);
        //推送京东设备状态
//        Map<String, Object> params = new HashMap<>();
//        params.put("id", LogicIdUtil.bussinessId());
//        Map<String, Object> protocol = new HashMap<>();
//        protocol.put("version", "1.0");
//        protocol.put("name", "JD-IOT-ESTATE-DEVICE");
//        Map<String, Object> client = new HashMap<>();
//        client.put("appid", "C4B1ZCFV8TOOP6NIVOCHZPCBP");
//        Map<String, Object> param = new HashMap<>();
//        String jdDeviceId = "1.2.156.156.12.11.743760662487891968";
//        if (StringUtils.isNotBlank(jdDeviceId)) {
//            param.put("deviceId", jdDeviceId);
//            param.put("status", "0");
//            params.put("protocol", protocol);
//            params.put("client", client);
//            params.put("params", param);
//            try {
//                params = DesEncryptUtil.getJdSign(JsonUtil.toJSON(params), PlatformConstants.JD_CHANGEONLINESTATUS_URL, "KJYWH5GYYVHABYPXHKE7QDDDA");
//                System.out.println(JsonUtil.toJSON(params));
//                System.out.println(HttpsPost.doJdPost("https://pre-api-estate.jd.com/api" + PlatformConstants.JD_CHANGEONLINESTATUS_URL, JsonUtil.toJSON(params)));
//            } catch (Exception e) {
//                log.error("【iot定时任务设备在线状态获取京东加密参数失败】", e);
//            }
//        }
        long startTime = System.currentTimeMillis();
        String photoUrl = "http://chuantu.xyz/t6/741/1611628557x-1404755288.jpg";
        try {
            String imageStr = imageToBase64ByOnline(photoUrl);
            log.info(imageStr);
            System.out.println("sss");
        } catch (Exception e) {
            e.printStackTrace();
        }

        long endTime = System.currentTimeMillis();
        System.out.println("【时间差值】" + (endTime - startTime));
    }
}
